package action.bookinfo;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import bizlogic.bookinfo.BookInfoService;
import bizlogic.bookinfo.domain.BookInfo;

@WebServlet("/bookinfoeditaction")
public class BookInfoEditAction extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    BookInfoService bookInfoService = new BookInfoService();
    // 记录bookid
    String bookid = "";


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if ("queryBookInfoByID".equals(request.getParameter("method"))) {
            queryBookInfoByID(request, response);
            bookid = request.getParameter("bookid");
        }
        if ("updateBookInfo".equals(request.getParameter("method"))) {
            updateBookInfo(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    /*
     * 功能需求：实例化一个Bookinfo实体，调用service层的相关方法，更新图书信息
     */
    public void updateBookInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String data = request.getParameter("data");
        BookInfo bookInfo = JSON.parseObject(data, BookInfo.class);
        // 将原来的bookid设置进实体
        bookInfo.setBookid(bookid);
        String str = bookInfoService.updateBookInfo(bookInfo);
        response.getWriter().write(str);

    }

    /*
     * 根据bookid得到bookinfo
     */
    public void queryBookInfoByID(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookId = request.getParameter("bookid");
        BookInfo queryBookInfoByID = bookInfoService.queryBookInfoByID(bookId);
        String json = JSONObject.toJSONString(queryBookInfoByID);
        response.getWriter().write(json);
    }

}
